/*!
 * \file ems_header.c
 *
 * \brief 消息头操作
 *
 * All Rights Reserved Copyright (C) 2014 broada,Co.,Ltd.
 *
 * \version 1.0
 * \author songbb
 * \date 2016/10/24
 *
 */

#include <stdio.h>

#include "frct_comm.h"

#include "ems_comm.h"
#include "ems_header.h"
#include "config.h"

int ems_header_detect(char *p_payload
                    , unsigned int ui_payload_len)
{
    EMS_PRINT_INFO("ems_header_detect...\n");

    if (ui_payload_len < 8)
        goto unknown;

    // 校验第5-8个字节是否为 0x9955eeaa
    if (memcmp(p_payload + 4, "\x99\x55\xee\xaa", 4) != 0)
        goto unknown;

    return APM_L7_IS_YES;
unknown:
    return APM_L7_IS_UNKNOWN;
}

int ems_header_unpack(char *p_payload
                   , unsigned int ui_payload_len
                   , Ems_header *p_st_ems_header)
{
    unsigned int *p_ui_total_size;
    unsigned int *p_ui_responseid;
    unsigned int ui_responseid;

    if (ui_payload_len < 8)
        goto error;

    // 校验第5-8个字节是否为 0x9955eeaa
    if (memcmp(p_payload + 4, "\x99\x55\xee\xaa", 4) != 0)
        goto error;

    if (ui_payload_len == 8)
    {
        p_st_ems_header->pkt_type = EMS_PKT_TYPE_NONE;
        p_st_ems_header->model_type = EMS_MODEL_TYPE_UNKNOWN;
        p_st_ems_header->ui_header_len = 8;
        p_st_ems_header->ui_pkt_len = 8;
        return FR_SUCC;
    }

    if (ui_payload_len < 13)
        goto error;

    p_ui_total_size = (unsigned int *) p_payload;
    p_st_ems_header->ui_pkt_len = (unsigned int) ntohl(*p_ui_total_size);

    p_st_ems_header->pkt_type = (Ems_pkt_type) *(p_payload + 8);
    switch (p_st_ems_header->pkt_type)
    {
        case EMS_PKT_TYPE_INIT_CONSUMER:
        case EMS_PKT_TYPE_DESTROY_CONSUMER:
        case EMS_PKT_TYPE_UNSUBSCRIBE_CONSUMER:
        case EMS_PKT_TYPE_START_CONSUMER:
        case EMS_PKT_TYPE_STOP_CONSUMER:
            p_st_ems_header->model_type = EMS_MODEL_TYPE_CONSUMER;
            break;
        case EMS_PKT_TYPE_INIT_PRODUCER:
        case EMS_PKT_TYPE_DESTROY_PRODUCER:
            p_st_ems_header->model_type = EMS_MODEL_TYPE_PRODUCER;
            break;
        default:
            p_st_ems_header->model_type = EMS_MODEL_TYPE_UNKNOWN;
    }

    p_ui_responseid = (unsigned int *) (p_payload + 9);
    ui_responseid = (unsigned int) ntohl(*p_ui_responseid);

    p_st_ems_header->ui_header_len = (unsigned) 13;

    EMS_PRINT_DBG("totalSize:[%u][0x%08x]\n", p_st_ems_header->ui_pkt_len, p_st_ems_header->ui_pkt_len);
    EMS_PRINT_DBG("pktType:[0x%02x][%s]\n", p_st_ems_header->pkt_type, EMS_PKT_TYPE2STR(p_st_ems_header->pkt_type));
    EMS_PRINT_DBG("responseID:[0x%08x]\n", ui_responseid);

    return FR_SUCC;
error:
    return FR_FAIL;
}
